package net.dodoman.serializable;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.log4j.Logger;

public class TestEntity {

	private static final String DEFAULT_OBJ_PATH = "d:\\objectFile.obj";

	private static Logger LOG = Logger.getLogger(TestEntity.class);

	private Entity entity;

	private SubEntity subEntity;

	public static void main(String[] args) throws FileNotFoundException,
			IOException, ClassNotFoundException {
		TestEntity testEntity = new TestEntity();
		testEntity.serilObj();
	}

	/**
	 * 构造方法初始化相关变量
	 */
	protected TestEntity() {
		entity = new Entity();
		subEntity = new SubEntity();
		entity.setAge(1);
		entity.setName("str");
		subEntity.setIdno("idno");
		subEntity.setAddress("address");
		subEntity.setPhoneno("phoneno");
		entity.setSubEntity(subEntity);
	}

	/**
	 * 序列化与反序列化
	 * 
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	protected void serilObj() throws FileNotFoundException, IOException,
			ClassNotFoundException {
		// 序列化对象
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
				DEFAULT_OBJ_PATH));
		out.writeObject(entity);

		// 反序列化对象
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(
				DEFAULT_OBJ_PATH));
		Entity myEntity = (Entity) in.readObject();
		consoleOut(myEntity);
	}

	private void byteObj() {
		// Utils.getBytesFromObject()
	}

	/**
	 * 输出控制台
	 * 
	 * @param myEntity
	 */
	private void consoleOut(Entity myEntity) {
		LOG.info(myEntity.getAge());
		LOG.info(myEntity.getName());
		SubEntity mySubEntity = myEntity.getSubEntity();
		LOG.info(mySubEntity.getIdno());
		LOG.info(mySubEntity.getAddress());
		LOG.info(mySubEntity.getPhoneno());
	}
}
